<template>
  <el-container>
    <el-header>
      <input type="file" @change="readtojson($event)" />
    </el-header>

    <el-main>
      <div id="src">
        <table>
          <tr v-for="item in colName" :key="item">
            <th>
              <el-button
                draggable="true"
                style="width: 100px"
                @dragstart="handle_start($event, item)"
                @dragend="handle_end"
                :value="item"
              >
                {{ item }}
              </el-button>
            </th>
          </tr>
        </table>
      </div>

      <div id="dest">
        <table>
          <tr v-for="(item, index) in destColName" :key="index">
            <th>
              <input
                type="text"
                @dragover="handle_over"
                @drop="handle_drop($event, index)"
                :value="transferColName[index]"
                :placeholder = "destColName2[index]"
                :required = "destColName2[index]"
              />
            </th>
            <th>
              <el-button style="width: 120px">{{ item }}</el-button>
            </th>
          </tr>
        </table>
      </div>
    </el-main>
    <el-footer>
      <el-button type="primary" @click="submit">提交</el-button>
    </el-footer>
  </el-container>
</template>

<script>
import { baseUrl } from "@/utils/request";
import axios from "axios";
export default {
  data() {
    return {
      file: null,
      wb: null,
      rABS: false,
      list: null, //表格内容
      colName: [],

      srcColName: [
        "姓名",
        "身份证号",
        "手机号",
        "学号",
        "密码",
        "年龄",
        "校区",
        "年级",
        "学院",
        "班级",
        "心理测试结果",
      ],
      destColName: [
        "student_name",
        "student_identityid",
        "student_phone",
        "student_id",
        "student_password",
        "student_age",
        "student_school",
        "student_grade",
        "student_object",
        "student_class",
        "student_testresult",
      ],
      destColName2: [
        "required",
        "required",
        "required",
        "required",
        "",
        "required",
        "required",
        "required",
        "required",
        "required",
        "",
      ],
      transferValue: "",
      transferColName: ["", "", "", "", "", "", "", "", "", "", ""],
      bind: {},
    };
  },
  methods: {
    readtojson(event) {
      this.file = event.target.files[0];
      var _this = this;
      var reader = new FileReader();
      reader.onload = function (e) {
        var data = e.target.result;
        if (_this.rABS) {
          _this.wb = XLSX.read(btoa(_this.fixdata(data)), {
            //手动转化
            type: "base64",
          });
        } else {
          _this.wb = XLSX.read(data, {
            type: "binary",
          });
        }
        var excelJson = XLSX.utils.sheet_to_json(
          _this.wb.Sheets[_this.wb.SheetNames[0]]
        );
        _this.list = excelJson;

        if (_this.list && _this.list.length >= 0) {
          let temp = _this.list[0];
          _this.colName = Object.keys(temp);
        }
      };
      if (this.rABS) {
        reader.readAsArrayBuffer(this.file);
      } else {
        reader.readAsBinaryString(this.file);
      }
    },
    fixdata(data) {
      var o = "",
        l = 0,
        w = 10240;
      for (; l < data.byteLength / w; ++l)
        o += String.fromCharCode.apply(
          null,
          new Uint8Array(data.slice(l * w, l * w + w))
        );
      o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
      return o;
    },
    submit() {
      //提交之前我们要做的事情应该有两件
      //第一件:绑定destColName和transferColName
      this.destColName.forEach((item, index) => {
        this.bind[item] = this.transferColName[index];
      });
      var aimlist = [];
      //第二件:遍历list，重新构造aimlist
      this.list.forEach((item) => {
        let temp = {};
        Object.getOwnPropertyNames(this.bind).forEach((key) => {
          if (this.bind[key]) {
            temp[key] = item[this.bind[key]];
          } else {
            temp[key] = null;
          }
        }, temp);
        aimlist.push(temp);
      });
      console.log(aimlist)
      axios.post(
          //url
          baseUrl + "/upload/uploadExcel",
          //jsondata
          {
            students: aimlist,
          }
        )
        .then((res) => {
          if (res.data.data === "导入成功！") {
            this.$message({
              type: "success",
              message: "数据导入成功!",
            });
            this.list = []
            aimlist = []
          } else {
            this.$message({
              type: "error",
              message: "数据导入失败!",
            });
          }

        });
    },
    handle_start(event, value) {
      this.transferValue = event.srcElement.value;
    },
    handle_end(event) {
      this.transferValue = "";
    },
    handle_over(event) {
      event.preventDefault(); //必须存在不能丢
    },
    handle_drop(event, index) {
      this.transferColName[index] = this.transferValue;
      event.preventDefault();
    },
  },
};
</script>
<style scoped>
.el-main {
  color: var(--el-text-color-primary);
  text-align: center;
  line-height: 35px;
  display: flex;
  /* justify-content: center; */
}
.el-header,
.el-footer {
  color: var(--el-text-color-primary);
  text-align: center;
  line-height: 80px;
  margin-bottom: 10px;
}

#src {
  width: 15%;
  text-align: right;
  margin-left: 25%;
}
#dest {
  width: 40%;
  text-align: left;
}
</style>
